package application.common.cron4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.cron4j.ITask;
import application.common.render.HttpClientResult;
import application.common.util.HttpUtil;
import application.common.util.ShiroUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class PictureTask implements ITask {
	private boolean isEnd = true;

	public void run() {
		if(isEnd) {
			if(ShiroUtil.getConfig()!=null && !StrKit.isBlank(ShiroUtil.getConfig().getSynURL())) {
				isEnd=false;
				try {
					HttpClientResult httpClientResult=HttpUtil.doGet(String.format("%s/api/cab/getPictures?cabinetId=%s", ShiroUtil.getConfig().getSynURL(),ShiroUtil.getAuth()));
					if(httpClientResult==null) {
						isEnd=true;
						return;
					}
					if(httpClientResult.getCode()!=200) {
						isEnd=true;
						return;	
					}
					String content=httpClientResult.getContent();
					if(StrKit.isBlank(content)) {
						isEnd=true;
						return;	
					}
					JSONObject jsonObject=JSONObject.fromObject(content);
					if(jsonObject==null) {
						isEnd=true;
						return;	
					}
					if(jsonObject.has("code")) {
						int code=jsonObject.getInt("code");
						if(code!=200) {
							isEnd=true;
							return;	
						}
						if(jsonObject.has("data")) {
							String data=jsonObject.getString("data");
							if(StrKit.isBlank(data)) {
								isEnd=true;
								return;	
							}
							JSONArray array=JSONArray.fromObject(data);
							if(array==null || array.size()==0) {
								isEnd=true;
								return;
							}
					
							ShiroUtil.getConfig().setDownPic("1");
							if(ShiroUtil.getConfig().update()) {
								List<String> list=new LinkedList<String>();
								for(Object object:array) {
									JSONObject row=JSONObject.fromObject(object);
									if(row!=null) {
										String id=row.getString("id");
										String format=row.getString("format");
										list.add(id+"."+format);
										downloadNet(id,format);
									}
								}
								File file = new File(ShiroUtil.getConfig().getPicturePath());
								if(file.exists()) {
									for(File file1:file.listFiles()) {
										if(!list.contains(file1.getName())) {
											file1.delete();
										}
									}
								}
								list=null;
								ShiroUtil.getConfig().setDownPic("0");
								ShiroUtil.getConfig().update();
							}else {
								isEnd=true;
							}
						}else {
							isEnd=true;
						}
					}else {
						isEnd=true;
					}
				}catch (Exception e) {
					isEnd=true;
				}
			}
			isEnd=true;
		}
	}

	public void stop() {
	}
	
	private void downloadNet(String pictureId, String format) throws Exception {// throws Exception
		int byteread = 0;
		URL url = null;
		InputStream inStream = null;
		FileOutputStream fs = null;
		URLConnection conn = null;
		try {
			File file=new File(ShiroUtil.getConfig().getPicturePath()+"/"+pictureId+"."+format);
			if(!file.exists()) {
				url = new URL(String.format("%s/api/cab/downPicture?pictureId=%s", ShiroUtil.getConfig().getSynURL(),pictureId));
				conn = url.openConnection();
				inStream = conn.getInputStream();
				fs = new FileOutputStream(file);
				int progressTotal = inStream.available();
				if (progressTotal > 0) {
					byte[] buffer = new byte[inStream.available()];
					while ((byteread = inStream.read(buffer)) != -1) {
						fs.write(buffer, 0, byteread);
					}
					fs.flush();
				}
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (IOException e) {
				}
			}
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
				}
			}
		}
	}
//	
//	public static void main(String[] args) {
//		int byteread = 0;
//		URL url = null;
//		InputStream inStream = null;
//		FileOutputStream fs = null;
//		URLConnection conn = null;
//		try {
//			File file=new File("d:/e00aec74d888414c8dcb4ee8fdd2f648.jpeg");
//			if(!file.exists()) {
//				url = new URL(String.format("%s/api/cab/downPicture?pictureId=%s","http://localhost:9090/jzg","e00aec74d888414c8dcb4ee8fdd2f648"));
//				conn = url.openConnection();
//				inStream = conn.getInputStream();
//				fs = new FileOutputStream(file);
//				int progressTotal = inStream.available();
//				if (progressTotal > 0) {
//					byte[] buffer = new byte[inStream.available()];
//					while ((byteread = inStream.read(buffer)) != -1) {
//						fs.write(buffer, 0, byteread);
//					}
//					fs.flush();
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (fs != null) {
//				try {
//					fs.close();
//				} catch (IOException e) {
//				}
//			}
//			if (inStream != null) {
//				try {
//					inStream.close();
//				} catch (IOException e) {
//				}
//			}
//		}
//	}

}
